package com.fancy.learncenter.net;

import com.google.gson.JsonObject;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 非凡学习验证签名，加密规则
 * Created by admin on 2017/4/20.
 */

public class FfLibraryNet {

    public static String getRequestSign(com.google.gson.JsonObject requestJson, String requestKey) {
        String md5 = getMD5Str(requestKey + requestJson.toString());
        String requestSign = getMD5Str(md5 + requestKey);
        return requestSign;
    }
    // 数据上传加密
    public static String getMD5Str(String str) {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(str.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            System.out.println("NoSuchAlgorithmException caught!");
            System.exit(-1);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        byte[] byteArray = messageDigest.digest();
        StringBuffer md5StrBuff = new StringBuffer();
        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
                md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
            } else {
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
            }
        }
        return md5StrBuff.toString();
    }

    public static com.google.gson.JsonObject generateRequestJson(Map<String, String> hashMap) {
        com.google.gson.JsonObject jsonObject = new JsonObject();
        List keyList = new ArrayList(hashMap.keySet());
        Collections.sort(keyList, new Comparator() {
            @Override
            public int compare(Object lhs, Object rhs) {
                String str1 = lhs.toString().toLowerCase();
                String str2 = rhs.toString().toLowerCase();
                return str1.compareTo(str2);
            }
        });
        for (Object key : keyList) {
            jsonObject.addProperty(String.valueOf(key), hashMap.get(key));
        }
        return jsonObject;
    }

}
